
const signale = require('signale');
const BabelRegister = require('@umijs/utils/lib/BabelRegister/BabelRegister').default;
const { resolve } = require('path');
const createMiddleware = require('@umijs/preset-built-in/lib/plugins/commands/dev/mock/createMiddleware').default;
const { getMockData } = require('@umijs/preset-built-in/lib/plugins/commands/dev/mock/utils');
const { createExpressMiddleware } = require('@smock/mock/lib/server/server');
const express = require('express');

const babelRegister = new BabelRegister();


const registerBabel = (files) => {
  babelRegister.setOnlyMap({
    key: 'mock',
    value: [...files],
  });
};

const app = express();
const port = process.env.PORT || 8000;
// app.get('/', (req, res) => res.send('Hello World!'));

const cwd = process.cwd();

const errors = [];
const ignore = [require('path').join(__dirname, './**/*.[jt]s'), 'node_modules/**'];

const mockResult = getMockData({
  cwd,
  ignore,
  registerBabel,
});
const { middleware } = createMiddleware({
  ...mockResult,
  // updateMockData: () => {
  //   const result = getMockData({
  //     cwd,
  //     ignore,
  //     registerBabel,
  //   });
  //   return result;
  // },
});

app.use(middleware);
app.use(createExpressMiddleware(port));

app.use(express.static(resolve(__dirname, '../dist')));

app.get('*', (_request, response) => {
  response.sendFile(resolve(__dirname, '../dist', 'index.html'));
});

app.listen(port, () => {

    console.log(`Example app listening on port http://localhost:${port} !`);
    if (errors.length) {
        signale.error(`Mock file parse failed`);
        errors.forEach(e => {
          console.error(e.message);
        });
    }
});
